<template>
  <div>
    <el-button :icon="DArrowLeft" type="primary" @click="router.back()" class="mb8">返回</el-button>

    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="站首管理" name="first">
        <el-button type="primary" @click="addStanding(1)">添加站首标签</el-button>
        <el-table :data="headData" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          style="height: calc(100vh - 250px)" ref="headDrag" :row-class-name="getRowClass">
          <el-table-column width="120" align="center">
            <template #default="scope">
              <i class="icon-handle" style="margin: 0 10px;">
                <el-icon>
                  <DCaret />
                </el-icon>
              </i>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="标签名" />
          <el-table-column label="标签类型">
            <template #default="scoped">
              {{
                sys_tag_type.find((e) => e.value === scoped.row.menuType)?.label
              }}
            </template>
          </el-table-column>
          <el-table-column prop="nameUrl" label="链接"/>
          <el-table-column label="图片" align="center">
            <template #default="scoped">
              <ImagePreview :src="scoped.row.host" width="50px" height="50px"></ImagePreview>
            </template>
          </el-table-column>
          <el-table-column prop="seq" label="排序" width="100" align="center" />
          <el-table-column prop="url" label="状态" align="center">
            <template #default="scoped">
              <el-switch v-model="scoped.row.status" active-text="开启" inactive-text="关闭" :active-value="1"
                :inactive-value="0" inline-prompt @change="handleStatusChange(scoped.row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="scoped">
              <el-button link type="primary" @click="handleHeard(1, scoped.row)">编辑</el-button>
              <el-button link type="danger" @click="handleHeard(0, scoped.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="站尾管理" name="second">
        <el-button type="primary" @click="addStanding(0)">添加站尾标签</el-button>
        <el-table :data="footData" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          style="height: calc(100vh - 250px)" ref="footDrag" :row-class-name="getRowClass">
          <el-table-column width="120" align="center">
            <template #default="scope">
              <i class="icon-handle" style="margin: 0 10px;">
                <el-icon>
                  <DCaret />
                </el-icon>
              </i>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="标签名" />
          <el-table-column prop="newType" label="标签类型">
            <template #default="scoped">
              {{
                sys_tag_type.find((e) => e.value === scoped.row.menuType)?.label
              }}
            </template>
          </el-table-column>
          <el-table-column prop="nameUrl" label="链接"/>
          <el-table-column prop="seq" label="排序" width="80" align="center" />
          <el-table-column label="状态" align="center">
            <template #default="scoped">
              <el-switch v-model="scoped.row.status" active-text="开启" inactive-text="关闭" :active-value="1"
                :inactive-value="0" inline-prompt @change="handleStatusChange(scoped.row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="scoped">
              <el-button link type="primary" @click="handleFootEdit(1, scoped.row)">编辑</el-button>
              <el-button link type="danger" @click="handleFootEdit(0, scoped.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <AddTag :TagVisible="TagVisible" @handleClose="handleClose" @handleSure="handleSure" :newType="newType"
      :websiteId="route.query.id" :languageId="route.query.languageId" :publicFrom="publicFrom"></AddTag>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { DArrowLeft, DCaret } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import AddTag from "./components/AddTag.vue";

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_tag_type } = proxy.useDict("sys_tag_type");
const newType = ref("");
const TagVisible = ref(false);
const publicFrom = ref({}); //公共赋值对象
const activeName = ref("first");

const headData = ref([]);
const footData = ref([]);
const mayDragHead = ref(true);//头部
const mayDragFoot = ref(true);//尾部
const draggedParent = ref(null)//获取父级
const draggedId = ref(null)//获取移动的id


onMounted(() => {
  getHeadList();
  getFootList();
  setTimeout(() => {
    handleDrag()
  }, 1000)
});
// 头部
const getHeadList = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      websiteId: Number(route.query.id),
      placeType: "top",
    },
  };
  site.general
    .site_website_menuList({
      data: from,
    })
    .then((res) => {
      headData.value = res.data;
    });
};
// 尾部
const getFootList = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      websiteId: Number(route.query.id),
      placeType: "bottom",
    },
  };
  site.general
    .site_website_menuList({
      data: from,
    })
    .then((res) => {
      footData.value = res.data;
    });
};
// 站首
const handleHeard = (type, row) => {
  if (type) {
    // 编辑
    TagVisible.value = true;
    newType.value = "top";
    publicFrom.value = row;
  } else {
    proxy.$modal.confirm("是否确认删除此数据项？").then(function () {
      publicDelete(row);
    });
  }
};
// 站底
const handleFootEdit = (type, row) => {
  if (type) {
    // 编辑
    TagVisible.value = true;
    newType.value = "bottom";
    publicFrom.value = row;
  } else {
    proxy.$modal.confirm("是否确认删除此数据项？").then(function () {
      publicDelete(row);
    });
  }
};

// 公共删除
const publicDelete = (row) => {
  site.general
    .site_website_menuDeletebatch({
      data: {
        ids: [row.id],
      },
    })
    .then((res) => {
      if (res.code === 200) {
        getHeadList();
        getFootList();
        proxy.$message.success("删除成功");
      }
    });
};
// 表格状态控制
const handleStatusChange = (e) => {
  proxy.$modal
    .confirm("是否确认修改此数据的状态？")
    .then(() => {
      return site.general
        .site_website_menuUpdatestatus({
          pathParams: {
            id: e.id,
          },
          params: {
            status: e.status,
          },
        })
        .then((response) => {
          proxy.$modal.msgSuccess("修改状态成功");
          handleSure();
        });
    })
    .catch(() => {
      if (e.status) {
        return (e.status = 0);
      } else {
        return (e.status = 1);
      }
    });
};
// 新增
const addStanding = (index) => {
  publicFrom.value = {};

  TagVisible.value = true;
  if (index) {
    newType.value = "top";
  } else {
    newType.value = "bottom";
  }
};
// 取消
const handleClose = () => {
  TagVisible.value = false;
};
const handleSure = (data) => {
  getHeadList();
  getFootList();
  TagVisible.value = false;
};
// 手动给 <tr> 添加 data-id
const getRowClass = ({ row }) => `row-id-${row.id}`;
const handleDrag = () => {
  const headTableBody = proxy.$refs["headDrag"].$el.querySelector(
    ".el-table__body-wrapper tbody"
  );
  proxy.Sortable.create(headTableBody, {
    animation: 150, // 拖拽动画
    handle: ".icon-handle", // 把手选择器
    filter: ".no-drag", // 禁用拖拽的类
    ghostClass: "blue-background-class",
    draggable: '.el-table__row',
    group: "tree", // 启用跨组拖拽
    onMove: (event) => {
      draggedId.value = event.dragged?.classList.value.match(/row-id-(\d+)/)?.[1];
      const relatedId = event.related?.classList.value.match(/row-id-(\d+)/)?.[1];

      // 获取拖拽元素的父级
      draggedParent.value = findParent(draggedId.value, headData.value);
      const relatedParent = findParent(relatedId, headData.value);

      // 如果拖拽的是子元素，并且目标位置的父级不同，则禁止移动
      if (draggedParent.value && draggedParent.value !== relatedParent) {
        mayDragHead.value = false;
        return false;
      } else {
        mayDragHead.value = true;
      }
    },
    onEnd: (event) => {
      const { oldIndex, newIndex } = event;
      if (!mayDragHead.value) return
      // console.log(draggedParent.value,'获取拖拽元素的父级');
      var newRowIndex
      var movedItem
      let menuIds = []

      if (draggedParent.value) {
        let newChildren = headData.value.find(e => e.id === draggedParent.value.id)?.children

        newRowIndex = findIndexById(draggedId.value, draggedParent.value.children);
        movedItem = newChildren.splice(newRowIndex, 1)[0];
        newChildren.splice(draggedId.value, 0, movedItem);
        menuIds = newChildren.map(item => item.id)
        console.log(newChildren[0]?.fatherId);
        portDrag('top', newChildren[0]?.fatherId, menuIds)
        // console.log(menuIds);
      } else {
        newRowIndex = findIndexById(draggedId.value, headData.value);
        movedItem = headData.value.splice(newRowIndex, 1)[0];
        headData.value.splice(draggedId.value, 0, movedItem);
        menuIds = headData.value.map(item => item.id)
        portDrag('top', 0, menuIds)
        // console.log( menuIds);
      }
    }
  });

  const footTableBody = proxy.$refs["footDrag"].$el.querySelector(
    ".el-table__body-wrapper tbody"
  );
  proxy.Sortable.create(footTableBody, {
    animation: 150, // 拖拽动画
    handle: ".icon-handle", // 把手选择器
    filter: ".no-drag", // 禁用拖拽的类
    ghostClass: "blue-background-class",
    draggable: '.el-table__row',
    group: "tree", // 启用跨组拖拽
    onMove: (event) => {
      draggedId.value = event.dragged?.classList.value.match(/row-id-(\d+)/)?.[1];
      const footRelatedId = event.related?.classList.value.match(/row-id-(\d+)/)?.[1];

      // 获取拖拽元素的父级
      draggedParent.value = findParent(draggedId.value, footData.value);
      const footRelatedParent = findParent(footRelatedId, footData.value);

      // 如果拖拽的是子元素，并且目标位置的父级不同，则禁止移动
      if (draggedParent.value && draggedParent.value !== footRelatedParent) {
        mayDragHead.value = false;
        return false;
      } else {
        mayDragHead.value = true;
      }
    },
    onEnd(event) {
      const { oldIndex, newIndex } = event;
      if (!mayDragHead.value) return
      var newRowIndex
      var movedItem
      let menuIds = []
      if (draggedParent.value) {
        let newChildren = footData.value.find(e => e.id === draggedParent.value.id)?.children

        newRowIndex = findIndexById(draggedId.value, draggedParent.value.children);
        movedItem = newChildren.splice(newRowIndex, 1)[0];
        newChildren.splice(draggedId.value, 0, movedItem);
        menuIds = newChildren.map(item => item.id)
        console.log(newChildren[0]?.fatherId);
        portDrag('bottom', newChildren[0]?.fatherId, menuIds)
        // console.log(menuIds);
      } else {
        newRowIndex = findIndexById(draggedId.value, footData.value);
        movedItem = footData.value.splice(newRowIndex, 1)[0];
        footData.value.splice(draggedId.value, 0, movedItem);
        menuIds = footData.value.map(item => item.id)
        portDrag('bottom', 0, menuIds)
        // console.log( menuIds);
      }
    },
  });
};


const findParent = (id, data) => { // 查找父级
  for (const item of data) {
    if (item.children?.some(child => child.id == id)) {
      return item;
    }
    if (item.children) {
      const found = findParent(id, item.children);
      if (found) return found;
    }
  }
  return null;
};
function findIndexById(id, list) {
  let index = -1;
  list.some((item, i) => {
    if (item.id == id) {
      index = i;
      return true;
    }
    if (item.children) {
      index = findIndexById(id, item.children);
      if (index !== -1) return true;
    }
    return false;
  });
  return index;
}
const portDrag = (placeType, fatherId, menuIds) => {
  // site.general.site_website_menuUpdatemenusort(
  //   {
  //     data: {
  //       websiteId: 0,
  //       placeType: '',
  //       fatherId: 0,
  //       menuIds: []
  //     }
  //   }
  // )
  site.general.site_website_menuUpdatemenusort(
    {
      data: {
        websiteId: Number(route.query.id),
        menuIds: menuIds,
        fatherId: fatherId,
        placeType: placeType
      }
    }
  ).then(res => {
    if (res.code === 200) {
      if (placeType === 'top') {
        headData.value = []
        getHeadList();
      } else {
        footData.value = []
        getFootList();
      }
    }
  })
}


</script>
<style lang="scss" scoped>
/* 展开/折叠箭头样式 */
.arrow-icon {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #606266;
}

.arrow-icon i {
  transition: transform 0.2s ease;
}
</style>
